package main

import (
	"geektime-go/week2/homework/repository"
	"geektime-go/week2/homework/repository/dao"
	"geektime-go/week2/homework/service"
	"geektime-go/week2/homework/web"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func main() {
	db := initDB()
	err := dao.InitTable(db)
	if err != nil {
		panic(err)
	}
	server := initWebServer()
	initUserHandler(server, db)

	err = server.Run(":8080")
	if err != nil {
		panic(err)
	}
}

func initDB() *gorm.DB {
	db, err := gorm.Open(mysql.Open("root:root@tcp(localhost:13316)/webook"))
	if err != nil {
		panic(err)
	}
	return db
}

func initWebServer() *gin.Engine {
	server := gin.Default()
	return server
}

func initUserHandler(server *gin.Engine, db *gorm.DB) {
	ud := dao.NewUserDao(db)
	ur := repository.NewUserRepo(ud)
	us := service.NewUserService(ur)
	c := web.NewUserServer(us)
	c.RegisterRoutes(server)
}
